package com.google.jessewilson.codesearch.io;

import java.util.List;

/**
 * Static utility methods for working with file paths.
 *
 * @author jessewilson
 */
public class Paths {

  /**
   * The length of the common postfix in the two paths.
   *
   * <p>For example, the result for inputs {@code /beer/molson/Canadian.txt} and
   * {@link /groceries/beverages/molson/Canadian.txt} is 2.
   */
  public static int commonPathLength(Path a, Path b) {
    List<String> aParts = a.getParts();
    List<String> bParts = b.getParts();
    int aLen = aParts.size();
    int bLen = bParts.size();

    int commonLength = 0;
    while(commonLength < aLen && commonLength < bLen) {
      String aPathPartI = aParts.get(aLen - 1 - commonLength);
      String bPathPartI = bParts.get(bLen - 1 - commonLength);
      if(aPathPartI.equals(bPathPartI)) {
        commonLength++;
      } else {
        break;
      }
    }

    return commonLength;
  }

}
